package com.xstudio.pvzreborn.capability;

import com.xstudio.pvzreborn.PVZReborn;
import com.xstudio.pvzreborn.block.entity.PVZMachineBlockEntityBase;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.eventbus.api.IEventBus;

public class CapManager {

	public static final Capability<Sunshine> SUNSHINE = CapabilityManager.get(new CapabilityToken<>() {
	});

	public static final Capability<DaveCoin> DAVE_COIN = CapabilityManager.get(new CapabilityToken<>() {
	});

	public static final Capability<PlantFood> PLANT_FOOD = CapabilityManager.get(new CapabilityToken<>() {
	});

	public static void init(IEventBus bus) {
		PVZReborn.LOGGER.info("Initializing capabilities");
		bus.addListener(CapManager::onRegisterCapabilities);
		MinecraftForge.EVENT_BUS.addGenericListener(Entity.class, CapManager::onAttachCapabilitiesBlockEntity);
		PVZReborn.LOGGER.info("Initialized capabilities");
	}

	public static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
		event.register(DaveCoin.class);
		event.register(Sunshine.class);
		event.register(PlantFood.class);
	}

	public static void onAttachCapabilitiesBlockEntity(AttachCapabilitiesEvent<Entity> event) {
		if (event.getObject() instanceof Player) {
			Sunshine energy = new Sunshine(PVZMachineBlockEntityBase.MAX_ENERGY);
			energy.setValue(50);
			event.addCapability(PVZReborn.prefix("sunshine"), new BaseCapProvider<>(energy, SUNSHINE));
			event.addCapability(PVZReborn.prefix("dave_coin"), new BaseCapProvider<>(new DaveCoin(), DAVE_COIN));
			event.addCapability(PVZReborn.prefix("plant_food"), new BaseCapProvider<>(new PlantFood(5), PLANT_FOOD));
		}
	}

}
